package com.smasher.location.actual;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.smasher.location.listener.LocationCallback;
import com.smasher.location.proxy.LocationNa;

import java.util.Locale;

public class LocationAMap implements LocationNa {

    public static final String TAG = "LOCATION_IMP";

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption option;
    private LocationCallback mCallback;
    private boolean isLocating = false;

    public LocationAMap() {

    }

    @Override
    public void init(Context context) {
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(context);
            //设置定位回调监听
            mLocationClient.setLocationListener(mLocationListener);

            option = new AMapLocationClientOption();
            option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
            option.setBeidouFirst(true);
            option.setNeedAddress(true);
            option.setOnceLocation(true);
            option.setHttpTimeOut(10000);
            option.setLocationCacheEnable(false);

            mLocationClient.setLocationOption(option);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void start() {
        AMapLocation amapLocation = getLastKnownLocation();
        if (amapLocation != null) {
            long time = amapLocation.getTime();
            long current = System.currentTimeMillis();
            if (current - time < 1000 * 60) {
                double x = amapLocation.getLongitude();
                double y = amapLocation.getLatitude();
                String formatValue = "%1f,%2f";
                String locationInfo = String.format(Locale.getDefault(), formatValue, x, y);
                if (!TextUtils.isEmpty(amapLocation.getAddress())) {
                    if (mCallback != null) {
                        mCallback.onSuccess(locationInfo, amapLocation.getAddress());
                    }
                }
            }
        }
        startLocation();
    }

    @Override
    public void stop() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            isLocating = false;
        }
    }

    @Override
    public void release() {
        if (mLocationClient != null) {
            mLocationClient.onDestroy();
            mLocationClient = null;
            isLocating = false;
        }
    }


    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。

                    double x = amapLocation.getLongitude();
                    double y = amapLocation.getLatitude();
                    String formatValue = "%1f,%2f";
                    String locationInfo = String.format(Locale.getDefault(), formatValue, x, y);

                    int gpsStatus = amapLocation.getGpsAccuracyStatus();
                    Log.d(TAG, "onLocationChanged: GpsAccuracyStatus=" + gpsStatus);

                    int locationType = amapLocation.getLocationType();
                    Log.d(TAG, "onLocationChanged: locationType=" + locationType);

                    String locationDetail = amapLocation.getLocationDetail();
                    Log.d(TAG, "onLocationChanged: locationDetail=" + locationDetail);

                    String address = amapLocation.getAddress();
                    String detail = getAddressDetail(amapLocation);
                    if (TextUtils.isEmpty(address)) {
                        address = detail;
                    }
                    if (mCallback != null) {
                        mCallback.onSuccess(locationInfo, address);
                    }
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e(TAG, "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    String pattern = "定位失败,错误码：d%";
                    int code = amapLocation.getErrorCode();
                    String message = String.format(pattern, code);
                    if (mCallback != null) {
                        mCallback.onFailed(message);
                    }
                }
            } else {
                if (mCallback != null) {
                    mCallback.onFailed("no amap location");
                }
            }

            if (mCallback != null) {
                mCallback.onCompleted();
            }
            isLocating = false;
        }
    };

    public void setCallback(LocationCallback callback) {
        mCallback = callback;
    }

    private String getAddressDetail(AMapLocation amapLocation) {
        StringBuilder sb = new StringBuilder();
        if (amapLocation != null) {
            String country = amapLocation.getCountry();
            if (!TextUtils.isEmpty(country)) {
                sb.append(country);
            }
            String province = amapLocation.getProvince();
            if (!TextUtils.isEmpty(province)) {
                sb.append(province);
            }
            String city = amapLocation.getCity();
            if (!TextUtils.isEmpty(city)) {
                sb.append(city);
            }
            String district = amapLocation.getDistrict();
            if (!TextUtils.isEmpty(district)) {
                sb.append(district);
            }
            String street = amapLocation.getStreet();
            if (!TextUtils.isEmpty(street)) {
                sb.append(street);
            }
        }
        return sb.toString();
    }

    private AMapLocation getLastKnownLocation() {
        AMapLocation amapLocation = null;
        if (mLocationClient != null) {
            amapLocation = mLocationClient.getLastKnownLocation();
        }
        return amapLocation;
    }

    private void startLocation() {
        if (isLocating) {
            Log.i(TAG, "startLocation: is locating");
//            if (mCallback != null) {
//                mCallback.onFailed("正在定位中...");
//            }
        }
        // 申请权限后做的操作
        if (mLocationClient != null) {
            Log.i(TAG, "startLocation: do");
            isLocating = true;
            //启动定位
            mLocationClient.startLocation();

        } else {
            if (mCallback != null) {
                mCallback.onFailed("定位组件初始化失败");
            }
        }
    }
}
